/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package knowledgebase.dao;

import java.sql.SQLException;
import java.util.List;
import knowledgebase.model.Document;
import knowledgebase.model.User;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

/**
 *
 * @author eugene
 */
@Repository("DocumentDAO")
public class DocumentDAOImpl implements DocumentDAO {

    HibernateTemplate hibernateTemplate;
    
    @Autowired
    public void setSessionFactory(SessionFactory sessionFactory) {
        hibernateTemplate = new HibernateTemplate(sessionFactory);
    }
    
    @Override
    public String saveDocument(Document doc) {
        return (String) hibernateTemplate.save(doc);
    }
    
    @Override
    public void updateDocument(Document doc) {
        hibernateTemplate.update(doc);
    }

    @Override
    public void removeDocument(String docId) {
        Document doc = (Document) hibernateTemplate.findByNamedParam("from Document d where d.id = :id", "id", docId).get(0);
        hibernateTemplate.delete(doc);
    }

    @Override
    public List<Document> findDocumentsByTitle(String docTitle) {
        return (List<Document>) hibernateTemplate.findByNamedParam("from Document where title like '%:docTitle%'", "docTitle", docTitle);
    }
    
    @Override
    public void updateDocumentHierarchy(final String docId, final String hierarchy) {
        hibernateTemplate.executeWithNativeSession(new HibernateCallback() {

            @Override
            public Object doInHibernate(Session sn) throws HibernateException, SQLException {
                Query query = sn.createQuery("update Document set hierarchy = :hierarchy where id = :id");
                query.setString("hierarchy", hierarchy);
                query.setString("id", docId);
                query.executeUpdate();
                return null;
            }
        });
    }

    @Override
    public List<Document> getDocumentsByOwner(User owner) {
        return hibernateTemplate.findByNamedParam("from Document where owner = :owner", "owner", owner);
    }
    
    @Override
    public Document getDocumentById(String id) {
        return hibernateTemplate.get(Document.class, id);
    }
    
    @Override
    public List<Document> getAllDocuments() {
        return (List<Document>) hibernateTemplate.find("from Document");
    }
}
